﻿using BJYJ_Admin.Core.Utils.SMUtils;
using Microsoft.AspNetCore.Mvc.Controllers;
using System.Reflection;

namespace BJYJ_Admin.Core.Utils.ResultUtils
{
    /// <summary>
    ///重新自定义返回结果封装，加密返回结果
    /// </summary>
    [UnifyModel(typeof(BJYJResult<>))]
    public class ResultProvider : IUnifyResultProvider
    {

        private bool CheckNoEncrypt(FilterContext context)
        {
            var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
            if (actionDescriptor == null) return false;
            return actionDescriptor.MethodInfo.GetCustomAttributes<NoEncryptAttribute>(true).Any() ||
                   actionDescriptor.ControllerTypeInfo.GetCustomAttributes<NoEncryptAttribute>(true).Any();
        }


        /// <summary>
        /// JWT 授权异常返回值
        /// </summary>
        /// <param name="context"></param>
        /// <param name="metadata"></param>
        /// <returns></returns>
        public IActionResult OnAuthorizeException(DefaultHttpContext context, ExceptionMetadata metadata) // Furion 4.9.3+ 支持
        {
            return new JsonResult(YourRESTfulResult(metadata.StatusCode, data: metadata.Data, errors: metadata.Errors)
                , UnifyContext.GetSerializerSettings(context));
        }

        /// <summary>
        /// 异常返回值
        /// </summary>
        /// <param name="context"></param>
        /// <param name="metadata"></param>
        /// <returns></returns>
        public IActionResult OnException(ExceptionContext context, ExceptionMetadata metadata)
        {
            bool shouldEncrypt = !CheckNoEncrypt(context);
            context.HttpContext.Response.Headers["X-Encrypted"] = shouldEncrypt.ToString().ToLower();
            return new JsonResult(YourRESTfulResult(metadata.StatusCode, data: metadata.Data, errors: metadata.Errors, shouldEncrypt: shouldEncrypt),
                UnifyContext.GetSerializerSettings(context));
        }

        /// <summary>
        /// 成功返回值
        /// </summary>
        /// <param name="context"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public IActionResult OnSucceeded(ActionExecutedContext context, object data)
        {
            bool shouldEncrypt = !CheckNoEncrypt(context);
            context.HttpContext.Response.Headers["X-Encrypted"] = shouldEncrypt.ToString().ToLower();
            return new JsonResult(YourRESTfulResult(StatusCodes.Status200OK, true, data, shouldEncrypt: shouldEncrypt),
                UnifyContext.GetSerializerSettings(context));
        }

        /// <summary>
        /// 验证失败返回值
        /// </summary>
        /// <param name="context"></param>
        /// <param name="metadata"></param>
        /// <returns></returns>
        public IActionResult OnValidateFailed(ActionExecutingContext context, ValidationMetadata metadata)
        {
            bool shouldEncrypt = !CheckNoEncrypt(context);
            context.HttpContext.Response.Headers["X-Encrypted"] = shouldEncrypt.ToString().ToLower();
            return new JsonResult(YourRESTfulResult(metadata.StatusCode ?? StatusCodes.Status400BadRequest, data: metadata.Data, errors: metadata.ValidationResult, shouldEncrypt: shouldEncrypt),// 如果需要只显示第一条错误，修改为：errors: metadata.FirstErrorMessage
                UnifyContext.GetSerializerSettings(context));
        }

        /// <summary>
        /// 特定状态码返回值
        /// </summary>
        /// <param name="context"></param>
        /// <param name="statusCode"></param>
        /// <param name="unifyResultSettings"></param>
        /// <returns></returns>
        public async Task OnResponseStatusCodes(HttpContext context, int statusCode, UnifyResultSettingsOptions unifyResultSettings)
        {
            // 设置响应状态码
            UnifyContext.SetResponseStatusCodes(context, statusCode, unifyResultSettings);

            // 默认情况下，并未设置 HTTP 状态码，所以返回为 200，如需设置可通过以下代码：
            // context.Response.StatusCode = statusCode;

            switch (statusCode)
            {
                // 处理 401 状态码
                case StatusCodes.Status401Unauthorized:
                    await context.Response.WriteAsJsonAsync(YourRESTfulResult(statusCode, errors: "401 Unauthorized")
                        , App.GetOptions<JsonOptions>()?.JsonSerializerOptions);
                    break;
                // 处理 403 状态码
                case StatusCodes.Status403Forbidden:
                    await context.Response.WriteAsJsonAsync(YourRESTfulResult(statusCode, errors: "403 Forbidden")
                        , App.GetOptions<JsonOptions>()?.JsonSerializerOptions);
                    break;
                default: break;
            }
        }
        private static BJYJResult<object> YourRESTfulResult(int statusCode, bool succeeded = default, object data = default, object errors = default, bool shouldEncrypt = true)
        {            
            object processedData;
            // 转换错误信息为字符串
            string errorMessage = ErrorConverter.ConvertToString(errors, succeeded);
            if (shouldEncrypt && succeeded == true)
            {
                // 执行加密处理
                processedData = SM4Encrypt.Encrypt_ECB(
                    JsonConvert.SerializeObject(data, new JsonSerializerSettings { ContractResolver = new DataToLower() }));
            }
            else
            {
                // 不加密，直接序列化,对属性转为小写   
                //processedData = JsonConvert.SerializeObject(data, new JsonSerializerSettings { ContractResolver = new DataToLower() }); 
                processedData = data;
            }

            return new BJYJResult<object>
            {
                StatusCode = statusCode,
                Successful = succeeded,
                Data = processedData,
                Msg = errorMessage,
                Code = succeeded ? 0 : 1,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            };
        }
    }
    // 必须是泛型类型
    public class BJYJResult<T>
    {
        /// <summary>
        /// 状态码
        /// </summary>
        public int? StatusCode { get; set; }

        /// <summary>
        /// 数据
        /// </summary>
        public T Data { get; set; }

        /// <summary>
        /// 执行成功
        /// </summary>
        public bool Successful { get; set; }

        /// <summary>
        /// 错误信息
        /// </summary>
        public string Msg { get; set; }

        /// <summary>
        /// 附加数据
        /// </summary>
        public object Extras { get; set; }

        /// <summary>
        /// 时间戳
        /// </summary>
        public long Timestamp { get; set; }


        /// <summary>
        /// layui表格状态码
        /// </summary>
        public int? Code { get; set; }
    }

}